package qdu.testsocket2;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class TestSocketServer {
    static ServerSocket ss;
    static List<ClientHandler> clientList;
    public static void main(String[] args) {
        clientList = new ArrayList<ClientHandler>();
        new TestSocketServer().initServer();    
    }
  
    static void showClientInfo() {
        System.out.println("已经有" + clientList.size() + "个客户端链接:");
        for(ClientHandler index : clientList){
            System.out.println("链接客户端IP:" + index.clienSocket.getInetAddress() + "客户端端口:" + index.clienSocket.getPort());
        }
    }

    void initServer(){
        try {
            ss = new ServerSocket(9999);
            while(true){
                try {
                    Socket clinetSocket = ss.accept();//阻塞侦听客户端链接
                    if(clientList!= null){
                        ClientHandler ch = new ClientHandler(clinetSocket);//创建客户端链接对应的线程对象
                        ch.start();//启动客户端线程，在该线程中去接受当前客户端发来的消息
                        clientList.add(ch);//客户端线程对象放入链表
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                showClientInfo();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }    
}
class ClientHandler extends Thread{//每一个客户端对应一个线程对象
    public Socket clienSocket;
    public ClientHandler(Socket clienSocket){
        this.clienSocket = clienSocket;
    }
    public void run(){
        while(clienSocket!= null && !clienSocket.isClosed()){
            BufferedReader br = null;
            try {
                br = new BufferedReader(
                    new InputStreamReader(clienSocket.getInputStream())
                );
                
                String message = br.readLine();
                System.out.println("客户端:" + clienSocket.getInetAddress() + "发来消息：\n" + message);
            } catch (Exception e) {
                System.out.println("接收消息异常");
                e.printStackTrace();
            }finally{
                try {
                    if(br!=null)
                        br.close();
                } catch (Exception e) {}
            }
        }
    }
}